package ubadbtools.recoveryLogAnalyzer.redo.gui.forms;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.filechooser.FileNameExtensionFilter;

import ubadbtools.recoveryLogAnalyzer.redo.common.RecoveryLog;
import ubadbtools.recoveryLogAnalyzer.redo.exceptions.GUIException;
import ubadbtools.recoveryLogAnalyzer.redo.gui.controllers.RecoveryAnalyzerFormController;
import ubadbtools.recoveryLogAnalyzer.redo.gui.etc.LogTableModel;
import ubadbtools.util.guiHelper.GUIHelper;
import ubadbtools.util.xml.XMLLib;




/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
@SuppressWarnings("serial")
public class RecoveryAnalyzerForm extends JFrame 
{
	//[start] Atributos
	private RecoveryAnalyzerFormController formControl = null; //Clase con la logica importante del formulario
	private File currentFile = null; //Si el archivo fue cargado o guardado, se guarda para ser propuesto ante un nuevo intento de guardar
	//[end]

	//[start] Constructor
    public RecoveryAnalyzerForm()
    {
        initComponents();
    }
    //[end]
    
	//[start] Métodos públicos
	//[start] getTableLog
	public JTable getTableLog()
	{
		return tableLog;
	}
	//[end]

	//[start] getItemsList
	public JList getItemsList()
	{
		return lstItems;
	}
	//[end]
	
	//[start] getTransactionsList
	public JList getTransactionsList()
	{
		return lstTransactions;
	}
	//[end]

	//[start] EnableUserControls
	/**
     * Habilita los controles que interactuan con el usuario
     */
	public void EnableUserControls()
	{
		btnAddItem.setEnabled(true);
		btnAddLogRecord.setEnabled(true);
		btnAddTransaction.setEnabled(true);
        btnAnalyzeLog.setEnabled(true);
        tableLog.setEnabled(true);
        lstItems.setEnabled(true);
        lstTransactions.setEnabled(true);
        SaveMenuItem.setEnabled(true);
	}
	//[end]
	
	//[end]
	
	//[start] Métodos privados
	 //[start] LoadLogFromFile
    private void LoadLogFromFile(File file) throws GUIException
	{
		 // Genero el log desde el archivo
		RecoveryLog log = null;
		try
		{
			log = (RecoveryLog)XMLLib.fromXML(new FileReader(file));
		}
		catch(Exception e)
		{
			throw new GUIException("El log que se quiere cargar está mal formado (" + e.getMessage() + ")");
		}
		
		// Genero un nuevo controlador para la nueva historia
		formControl = RecoveryAnalyzerFormController.CreateController(this, log);
	}
    //[end]
    
    //[start] SaveLogToFile
    private void SaveLogToFile(File file) throws GUIException
	{
		// Obtengo la historia desde el controlador
		RecoveryLog log = formControl.GetLog();
		 
		try
		{
			XMLLib.toXML(log,new FileWriter(file));
		}
		catch(Exception e)
		{
			throw new GUIException("El log que se quiere guardar es inválido (" + e.getMessage() + ")");
		}
	}
    //[end]
    
	//[end]
	
    //[start] InitsComponents (AUTO-GENERATED)
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tableLog = new javax.swing.JTable();
        btnAnalyzeLog = new javax.swing.JButton();
        btnAddItem = new javax.swing.JButton();
        btnAddTransaction = new javax.swing.JButton();
        btnAddLogRecord = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstTransactions = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        lstItems = new javax.swing.JList();
        fileMenuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        NewMenuItem = new javax.swing.JMenuItem();
        LoadMenuItem = new javax.swing.JMenuItem();
        SaveMenuItem = new javax.swing.JMenuItem();
        ExitMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Analizador de log");
        setResizable(false);

        tableLog.setModel(new LogTableModel());
        tableLog.setEnabled(false);
        tableLog.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tableLog.getTableHeader().setResizingAllowed(false);
        tableLog.getTableHeader().setReorderingAllowed(false);
        tableLog.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableLogMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tableLog);

        btnAnalyzeLog.setEnabled(false);
        btnAnalyzeLog.setLabel("Analizar Log");
        btnAnalyzeLog.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAnalyzeLogActionPerformed(evt);
            }
        });

        btnAddItem.setText("Agregar ítem");
        btnAddItem.setEnabled(false);
        btnAddItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddItemActionPerformed(evt);
            }
        });

        btnAddTransaction.setText("Agregar Transacción");
        btnAddTransaction.setEnabled(false);
        btnAddTransaction.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddTransactionActionPerformed(evt);
            }
        });

        btnAddLogRecord.setText("Agregar Registro de Log");
        btnAddLogRecord.setEnabled(false);
        btnAddLogRecord.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddLogRecordActionPerformed(evt);
            }
        });

        lstTransactions.setModel(new DefaultListModel());
        lstTransactions.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lstTransactions.setEnabled(false);
        lstTransactions.setLayoutOrientation(javax.swing.JList.HORIZONTAL_WRAP);
        lstTransactions.setVisibleRowCount(1);
        jScrollPane2.setViewportView(lstTransactions);

        jLabel1.setText("Transacciones");

        jLabel2.setText("Items");

        lstItems.setModel(new DefaultListModel());
        lstItems.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lstItems.setEnabled(false);
        lstItems.setLayoutOrientation(javax.swing.JList.HORIZONTAL_WRAP);
        lstItems.setVisibleRowCount(1);
        jScrollPane3.setViewportView(lstItems);

        fileMenu.setText("Archivo");

        NewMenuItem.setText("Nuevo");
        NewMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NewMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(NewMenuItem);

        LoadMenuItem.setText("Cargar");
        LoadMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LoadMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(LoadMenuItem);

        SaveMenuItem.setText("Guardar");
        SaveMenuItem.setEnabled(false);
        SaveMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(SaveMenuItem);

        ExitMenuItem.setText("Salir");
        ExitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(ExitMenuItem);

        fileMenuBar.add(fileMenu);

        setJMenuBar(fileMenuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 610, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(btnAddTransaction, javax.swing.GroupLayout.DEFAULT_SIZE, 240, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnAddItem, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnAddLogRecord, javax.swing.GroupLayout.DEFAULT_SIZE, 377, Short.MAX_VALUE))
                        .addGap(52, 52, 52)
                        .addComponent(btnAnalyzeLog, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAddItem)
                    .addComponent(btnAddTransaction))
                .addGap(3, 3, 3)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAddLogRecord)
                    .addComponent(btnAnalyzeLog))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 339, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    //[end]
    
    //[start] Eventos
    private void btnAddLogRecordMouseClicked(java.awt.event.MouseEvent evt)
    {//GEN-FIRST:event_btnAddStepMouseClicked

    }//GEN-LAST:event_btnAddStepMouseClicked

	private void btnAnalyzeLogMouseClicked(java.awt.event.MouseEvent evt)
    {//GEN-FIRST:event_btnAnalyzeScheduleMouseClicked

    }//GEN-LAST:event_btnAnalyzeScheduleMouseClicked

    private void tableLogMouseClicked(java.awt.event.MouseEvent evt)
    {//GEN-FIRST:event_tableScheduleMouseClicked
        if(tableLog.isEnabled())
        {
	    	// Verifico si hubo un doble click
	    	if(evt.getClickCount() == 2)
	        {
	        	// Lanzo el editor de log record para el record sobre la que se hizo doble click en la tabla
	    		try
				{
					formControl.EditLogRecord(tableLog.getSelectedRow());
				}
				catch (GUIException ex)
				{
					GUIHelper.showErrorMessage(this,"Ocurrió un error al editar el registro de log: " + ex.getMessage());
				}
	        }
        }
    }//GEN-LAST:event_tableScheduleMouseClicked

    private void btnAddTransactionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddTransactionActionPerformed
    	if(btnAddTransaction.isEnabled())
    	{
			formControl.AddNewTransaction();
    	}
    }//GEN-LAST:event_btnAddTransactionActionPerformed

    private void btnAddItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddItemActionPerformed
    	if(btnAddItem.isEnabled())
    	{
			formControl.AddNewItem();
    	}
    }//GEN-LAST:event_btnAddItemActionPerformed

    private void btnAddLogRecordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddLogRecordActionPerformed
    	if(btnAddLogRecord.isEnabled())
    	{
			formControl.AddNewLogRecord();
    	}
    }//GEN-LAST:event_btnAddLogRecordActionPerformed

    private void btnAnalyzeLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAnalyzeLogActionPerformed
        if(btnAnalyzeLog.isEnabled())
        {
        	formControl.AnalyzeLog();
        }
    }//GEN-LAST:event_btnAnalyzeLogActionPerformed

    private void NewMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NewMenuItemActionPerformed
        // Creo el controlador y lo inicializo
        formControl = RecoveryAnalyzerFormController.CreateController(this);

        // Por último, pongo en null al archivo cargado indicando que es un nuevo log
        currentFile = null;
    }//GEN-LAST:event_NewMenuItemActionPerformed

    private void LoadMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoadMenuItemActionPerformed
    	JFileChooser fileChooser = new JFileChooser();

	    //Sólo permito que se agreguen .xml
    	fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("XML file", "xml"));
        fileChooser.setAcceptAllFileFilterUsed(false);

        //Muestro el dialog
        int dialogResult = fileChooser.showDialog(this,"Cargar");

        //Si seleccionaron algún archivo...
        if (dialogResult == JFileChooser.APPROVE_OPTION)
        {
            File file = fileChooser.getSelectedFile();
            try
            {
            	//Cargo el log a partir del XML
            	LoadLogFromFile(file);
            }
            catch(GUIException ex)
            {
            	GUIHelper.showErrorMessage(this,"Ocurrió un error al cargar el log: " + ex.getMessage());
            }

            //Me guardo el archivo cargado así cuando quieren guardar ya tienen todo
            currentFile = file;
        }
    }//GEN-LAST:event_LoadMenuItemActionPerformed

    private void SaveMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveMenuItemActionPerformed
		if(SaveMenuItem.isEnabled())
		{
			JFileChooser fileChooser = new JFileChooser();

		    //Sólo permito que se agreguen .xml
	    	fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("XML file", "xml"));
	        fileChooser.setAcceptAllFileFilterUsed(false);

	        //Si el log fue cargado, propongo guardar el mismo archivo
	        if(currentFile != null)
	        	fileChooser.setCurrentDirectory(currentFile);

	        //Muestro el dialog
	        int dialogResult = fileChooser.showDialog(this, "Guardar");

	        //Si seleccionaron algún archivo...
	        if (dialogResult == JFileChooser.APPROVE_OPTION)
	        {
	            File file = fileChooser.getSelectedFile();

	            // Si el archivo no tiene extension, se la agrego
	            if(file.getName().indexOf(".") == -1)
	            {
	            	file = new File(file.getAbsolutePath() + ".xml");
	            }

	            try
	            {
	            	//Guardo el log en formato XML
	            	SaveLogToFile(file);
	            }
	            catch(GUIException ex)
	            {
	            	GUIHelper.showErrorMessage(this,"Ocurrió un error al guardar el log: " + ex.getMessage());
	            }

	            //Me guardo el path del archivo así cuando quieren guardar ya tienen todo
	            currentFile = file;
	        }
		}
    }//GEN-LAST:event_SaveMenuItemActionPerformed

    private void ExitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitMenuItemActionPerformed
    	System.exit(0);
    }//GEN-LAST:event_ExitMenuItemActionPerformed
    //[end]
    
    //[start] Variables Form (AUTO-GENERATED)
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem ExitMenuItem;
    private javax.swing.JMenuItem LoadMenuItem;
    private javax.swing.JMenuItem NewMenuItem;
    private javax.swing.JMenuItem SaveMenuItem;
    private javax.swing.JButton btnAddItem;
    private javax.swing.JButton btnAddLogRecord;
    private javax.swing.JButton btnAddTransaction;
    private javax.swing.JButton btnAnalyzeLog;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenuBar fileMenuBar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JList lstItems;
    private javax.swing.JList lstTransactions;
    private javax.swing.JTable tableLog;
    // End of variables declaration//GEN-END:variables
    //[end]
}
